<style lang="less" scoped>
@import "../assets/css/config.less";
.send-comment-btn {
  min-width: 70px;
  height: 40px;
  margin: auto auto auto 10px;
  padding: 5px 12px;
  font-size: 14px;
  background-color: @color1;
  border: 0;
  color: @white;
  border-radius: 4px;
  outline: none;
}
.send-comment {
  display: flex;
  justify-content: space-between;
}

.send-comment-btn:hover {
  background-color: @color2;
}
.time {
  // position: absolute;
  font-size: 14px;
  // right: 60px;
  color: #8a8a8a;
  font-weight: 500;
}
.user-content {
  float: right;
  // width: 93%;
  flex: 1;
  margin-left: 20px;
  text-align: left;
}
.user-content h3 {
  display: flex;
  justify-content: space-between;
}
.comment-text {
  width: 100%;
  font-size: 14px;
  padding: 5px 0;
  word-break:break-all;       //按字符截断换行 /* 支持IE和chrome，FF不支持*/
  word-wrap:break-word;    //按英文单词整体截断换行  /* 以上三个浏览器均支持 */
}
.confirm{
  position: fixed;
  top:0;
  left: 0;
  bottom: 0;
  right: 0;
  background-color: rgba(0, 0, 0, 0.5);
  z-index: 3300;
  display: flex;
  justify-content: center;
  align-items: center;
}
.message{
  z-index: 4000!important;
}

.comment-area .user-pic{
  width: 40px;
  height: 40px;
  border-radius: 50%;
  overflow: hidden;
  float: left;
  background-color: @white;
  display: flex;
  flex-direction: row;
  align-items: flex-end;
  justify-content: center;
  border:1px solid #ccc;
}
.user-pic img{
  width: 80%;
  height: 80%;
  // margin-bottom: -6px;
}
</style>

<template>
  <div>
    <div class="focus-card">
      <div class="comment-item">
        <div class="send-comment">
          <el-input v-model="input" placeholder="请写下您的问题..." ref="commentInput"></el-input>
          <!-- <div class="comment-input" ref="editor" id="input" contenteditable="true"></div> -->
          <button class="send-comment-btn" @click="submitComment(true)">发布</button>
        </div>
        <div>
          <!-- <img :src="`../../static/pic/wechat/${ i + 100 }.${ i < 100 ? 'gif' : 'png'}`" v-for="i in 119" :key="i"> -->
          <!-- <img :src="`../../static/pic/wechat/202.png`"> -->
        </div>
        <div
          style="font-size: 15px; text-align: center;padding: 10px"
          v-if="commentList.length === 0 && addCommentFlag === false"
        >这里还没有任何内容，快来写下你的问题吧~</div>
        <div
          v-for="(com,key) in commentList"
          style="width: 100%;display: flex; padding: 10px 10px 0 10px;"
          :style="key === commentList.length-1 ? '' : 'border-bottom: 1px solid #F1F1F1;'"
          :key="key"
        >
          <div class="user-pic">
            <img :src="`../static/pic/avatars/${com.avatar}`" alt="头像" />
          </div>
          <div class="user-content">
            <h3>
              <span>
                {{com.authorUsername}}
                <span>({{com.authorRole==='0'?'学生':com.authorRole==='1'?'超管':com.authorRole==='2'?'助教':'老师'}})</span>
              </span>

              <span class="time">{{formatDate(com.time)}}</span>
            </h3>
            <p class="comment-text" v-if="com.content">{{com.content.replace(/<.*?>/ig,"")}}</p>
            <div class="button-list">
              <div
                :class="com.likeFlag?'zaning':'zan'"
                @click="likeIt(key, true, null)"
              >{{ com.likeCount }}</div>
              <div v-if="user.UUID !== com.authorUUID" @click="showReplyInput(key)" class="reply">
                <span class="space"></span>
                {{showReplyInputFlag === key ? '取消回复' : '回复'}}
              </div>
              <a
                href
                class="delete"
                @click.prevent="deletePostingHandle(com._id, '')"
                v-if="user.UUID === com.authorUUID"
              >删除</a>
            </div>
            <div v-if="showReplyInputFlag === key" class="reply-comment">
              <el-input
                ref="input"
                v-model="replyInput"
                :placeholder="`回复 ${ com.authorUsername }`"
              ></el-input>
              <button class="send-comment-btn" @click="submitComment(false, key)">回复</button>
            </div>

            <div v-for="(ans,index) in com.reply" style="width: 100%;display: flex;border-top: 1px solid #F1F1F1;padding-top: 5px" :key="index">
              <div class="user-pic" style="padding-top: 5px;">
                <img :src="`../static/pic/avatars/${ans.avatar}`" alt="头像" />
              </div>
              <div class="user-content">
                <h3 class="spacing">
                  <span>
                    {{ans.authorUsername}}
                    <span
                      class="spacing authorrole"
                    >({{ans.authorRole==='0'?'学生':ans.authorRole==='1'?'超管':ans.authorRole==='2'?'助教':'老师'}})</span>
                  </span>
                  <span class="time">{{formatDate(ans.time)}}</span>
                </h3>
                <p class="comment-text" v-if="ans.content">{{ans.content.replace(/<.*?>/ig,"")}}</p>
                <!--<a v-on:click="comtClick($event,item)" href="javascript:;" class="btn btn-comment">-->
                <!--<span class="el-icon-chat-square"></span>{{show_name}}-->
                <!--</a>-->
                <div class="button-list">
                  <div
                    :class="ans.likeFlag?'zaning':'zan'"
                    @click="likeIt(key, false, ans._id, index)"
                  >{{ ans.likeCount }}</div>
                  <!-- <div v-if="user.UUID !== com.authorUUID" class="reply">
                            <span class="el-icon-chat-square"></span>回复
                  </div>-->
                  <a href class="delete" v-if="user.UUID === ans.authorUUID" @click.prevent="deletePostingHandle('', ans._id)">删除</a>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
    <div v-if="confirmFlag" class="confirm">
      <div class="el-message-box">
        <div class="el-message-box__header">
          <div class="el-message-box__title">提示</div>
          <button type="button" class="el-message-box__headerbtn" @click="cancelDel">
            <i class="el-message-box__close el-icon-close"></i>
          </button>
        </div>
        <div class="el-message-box__content">
          <div class="el-message-box__container">
            <div class="el-message-box__status el-icon-warning"></div>
            <div class="el-message-box__message">此操作将永久删除该评论, 是否继续?</div>
          </div>
        </div>
        <div class="el-message-box__btns">
          <button type="button" class="el-button el-button--default el-button--small" @click="cancelDel">取消</button>
          <button type="button" class="el-button el-button--default el-button--small el-button--primary" @click="confirmDel">确认</button>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { like_and_cancel, addOnePosting, getPostings, deletePosting } from "../api/api";
export default {
  name: "comment",
  data() {
    return {
      commentList: [],
      addCommentFlag: false,
      input: "",
      user: null,
      showReplyInputFlag: -1,
      replyInput: "",
      confirmFlag: false,
      delPostingId: '',
      delReplyId: '',
      menu: ''
    };
  },
  props: ["point"],
  created(){
  },
  mounted() {
    this.user = JSON.parse(this.$store.state.user);
    this.$nextTick(() => {
      this.getCommentList();
    })
    
  },
  methods: {
    cancelDel(){
      this.confirmFlag = false;
      this.delPostingId = '';
      this.delReplyId = '';
      this.$Message.success('已取消删除');
    },
    confirmDel(){
      deletePosting({
        postingId: this.delPostingId,
        replyId: this.delReplyId
      }).then(res => {
        if(res.state === true) {
          this.confirmFlag = false;
          this.delPostingId = '';
          this.delReplyId = '';
          this.$Message.success('删除评论成功');
          this.getCommentList();
        } else {
          this.$Message.error(res.msg)
        }
      }).catch(err => {
        this.$Message.error(err)
      })
    },
    deletePostingHandle(postingId, replyId){
      this.confirmFlag = true;
      this.delPostingId = postingId;
      this.delReplyId = replyId;
    },
    showReplyInput(key) {
      if (this.showReplyInputFlag === key) {
        this.showReplyInputFlag = -1;
        this.replyInput = "";
        return;
      }
      this.replyInput = "";
      this.showReplyInputFlag = key;
      this.$nextTick(() => {
        this.$refs.input[0].focus();
      });
    },
    likeIt(index, postOrNot, replyId, index2) {
      if (postOrNot) {
        like_and_cancel({
          UUID: this.user.UUID,
          posting_id: this.commentList[index]._id,
          postOrNot: postOrNot,
        })
          .then((res) => {
            if (res.state === true) {
              this.commentList[index].likeCount = res.likeCount;
              this.commentList[index].likeFlag = res.flag;
            } else {
              this.$message({
                customClass: "message",
                type: "error",
                message: "点赞失败",
              });
            }
          })
          .catch((err) => {
            this.$message({
              customClass: "message",
              type: "error",
              message: err.status,
            });
          });
        return;
      }
      like_and_cancel({
        UUID: this.user.UUID,
        posting_id: this.commentList[index]._id,
        postOrNot: postOrNot,
        reply_id: replyId,
      })
        .then((res) => {
          if (res.state === true) {
            this.commentList[index].reply[index2].likeCount = res.likeCount;
            this.commentList[index].reply[index2].likeFlag = res.flag;
          } else {
            this.$Message.error("点赞失败");
          }
        })
        .catch((err) => {
          this.$Message.error(err);
        });
    },
    getCommentList() {
      getPostings({
        UUID: this.user.UUID,
        point_id: this.point._id,
      })
        .then((response) => {
          if (response.state === true) {
            this.commentList = response.result;
            // console.log(this.commentList)
          } else {
            this.$Message.error(response.msg);
          }
        })
        .catch((error) => {
          this.$Message.error(error.status);
        });
    },
    formatDate(time) {
      let t = new Date(time);
      let year = t.getFullYear();
      let month =
        t.getMonth() + 1 < 10 ? `0${t.getMonth() + 1}` : t.getMonth() + 1;
      let date = t.getDate() < 10 ? `0${t.getDate()}` : t.getDate();
      let hour = t.getHours() < 10 ? `0${t.getHours()}` : t.getHours();
      let minute = t.getMinutes() < 10 ? `0${t.getMinutes()}` : t.getMinutes();
      return `${year}-${month}-${date}　${hour}:${minute}`;
    },
    addComment() {
      if (this.addCommentFlag) {
        this.addCommentFlag = false;
        return; 
      }
      this.addCommentFlag = true;
      this.$nextTick(() => {
        this.$refs.commentInput.focus();
      });
    },
    submitComment(postOrNot, key) {
      if (postOrNot) {
        if (this.input.trim().length == 0) {
          this.$Message.error("评论内容不能为空！");
          return;
        }
        addOnePosting({
          postOrNot: postOrNot,
          menu: this.point.menu,
          point_title: this.point.title,
          point_id: this.point._id,
          authorUUID: this.user.UUID,
          authorUsername: this.user.username,
          authorRole: this.user.userGroup,
          time: new Date().getTime(),
          content: this.input,
          avatar: this.user.avatar
        })
          .then((response) => {
            if (response.state === true) {
              this.$Message.success("提交成功");
              this.commentList.push(response.posting);
              this.input = "";
            } else {
              this.$Message.error("提交失败！ " + response.msg);
            }
          })
          .catch((error) => {
            this.$Message.error(error.status);
          });
      } else {
        if (this.replyInput.trim().length == 0) {
          this.$Message.error("回复内容不能为空！");
          return;
        }
        addOnePosting({
          postOrNot: postOrNot,
          postingId: this.commentList[key]._id,
          content: this.replyInput,
          authorUUID: this.user.UUID,
          authorUsername: this.user.username,
          authorRole: this.user.userGroup,
          replyToName: this.commentList[key].authorUsername,
          replyToUUID: this.commentList[key].authorUUID,
          replyToId: this.commentList[key]._id,
          time: new Date().getTime(),
          likeCount: 0,
          avatar: this.user.avatar
        })
          .then((response) => {
            if (response.state === true) {
              this.$Message.success("提交成功");
              // 回复成功，收起输入框，清空输入内容
              this.showReplyInputFlag = -1;
              this.replyInput = "";
              this.commentList[key].reply.push(response.msg);
            } else {
              this.$Message.error("提交失败！ " + response.msg);
            }
          })
          .catch((error) => {
            this.$Message.error(error.status);
          });
      }
    },
  },
};
</script>